<template>
  <div class="container">
    <div class="sign_in">
      <div class="login_img">
        <!-- <img src="@/assets/imgs/login/logo.png" class="login_logo" /> -->
      </div>
      <div class="sign_div">
        <div class="login_form">
          <div class="login_item">
            <div class="sign_top">
              <language class="sign_top_select" />
            </div>

            <div style="width: 296px; height: 64px; margin-bottom: 55px;">
              <img src="@/assets/imgs/login/logo_joltzly@2x.png" class="login_logo" style="width: 296px; height: 64px;" />
            </div>
                        
            <div class="sign_title">
              <span class="sign_title_login">{{
                $t('m.Account_resetPasswords')
              }}</span>
            </div>

            <!--忘记密码--->
            <el-form :model="form" :rules="rules" ref="form">
              <!--phone-->
              <div v-if="forgetPwdStep == 1">
                <div class="sign_form_title">
                  {{ $t('m.Login_Phone_Number') }}
                </div>
                <el-form-item prop="phone" class="sign_form_phone">
                  <country-code
                    :code-number.sync="form.code"
                    @select="selectCountry"
                    id="box"
                  />
                  <el-input
                    :placeholder="$t('m.Enterphonenumber')"
                    clearable
                    @input="changePhone"
                    v-model="form.phone"
                    :maxlength="15"
                    class="sign_form_input sign_form_input2"
                    :style="widthStyle"
                  />
                </el-form-item>
              </div>
              <!--验证码-->
              <div v-if="forgetPwdStep == 1">
                <div class="sign_form_title">
                  {{ $t('m.VerificationCode') }}
                </div>
                <el-form-item class="sign_form_code" prop="msgCode">
                  <el-input
                    :maxlength="4"
                    @input="changeCode"
                    :placeholder="$t('m.PleaseEnterTheVerificationCode')"
                    clearable
                    v-model="form.msgCode"
                    class="sign_form_input"
                  />
                  <el-button
                    :class="
                      msgKey ? 'sign_code sign_code_disabled' : 'sign_code'
                    "
                    :disabled="msgKey"
                    @click="handleSend"
                    >{{ msgText }}</el-button
                  >
                </el-form-item>
              </div>
              <!--password-->
              <div v-if="forgetPwdStep == 2">
                <div class="sign_form_title">
                  {{ $t('m.NewPassword') }}
                </div>
                <el-form-item prop="password">
                  <el-input
                    type="password"
                    :maxlength="16"
                    show-password
                    :placeholder="$t('m.NewPassword')"
                    clearable
                    v-model="form.password"
                    @input="changePassword"
                    class="sign_form_input"
                  />
                </el-form-item>
              </div>
              <!--confirm password-->
              <div v-if="forgetPwdStep == 2">
                <div class="sign_form_title">
                  {{ $t('m.ReEnterBewPassword') }}
                </div>
                <el-form-item prop="confirmPassword">
                  <el-input
                    type="password"
                    :maxlength="16"
                    show-password
                    :placeholder="$t('m.Login_Code_Input_Password_Again')"
                    clearable
                    v-model="form.confirmPassword"
                    @input="changePasswords"
                    class="sign_form_input"
                  >
                  </el-input>
                </el-form-item>
              </div>
            </el-form>

            <!--提交按钮-->
            <el-button class="sign_btn" @click="submit">
              {{ $t('m.Next') }}
            </el-button>

            <div class="sign_bottom">
              <span @click="$router.push('/login')"
                >{{ $t('m.Login') }}<i class="el-icon-arrow-right"></i
              ></span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import CountryCode from '../../components/country-code.vue'
import Language from '@/components/language.vue'

export default {
  components: { Language, CountryCode },
  // inject: ['reload'],
  name: 'login',

  data () {
    // 验证国家码+手机
    const validatorCodePhone = (rule, value, callback) => {
      if (!this.form.code) {
        callback(new Error(this.$t('m.pleaseChoose')))
        return
      } else if (value == '' || !value) {
        callback(new Error(this.$t('m.Enterphonenumber')))
        return
      } else if (!this.$reg.mobile.test(value)) {
        callback(new Error(this.$t('m.Shop_Created_shop_phone')))
        return
      } else {
        callback()
      }
    }
    // 验证密码
    const checkPassword = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{8,16}$/
      if (!value) {
        return callback(new Error(this.$t('m.Enterpassword')))
      } else if (!reg.test(value)) {
        return callback(new Error(this.$t('m.Set_login_password')))
      } else {
        callback()
      }
    }
    const checkPasswords = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{8,16}$/
      if (!value) {
        return callback(new Error(this.$t('m.Login_Code_Input_Password_Again')))
      } else if (!reg.test(value)) {
        return callback(new Error(this.$t('m.Set_login_password')))
      } else if (value != this.form.password) {
        return callback(new Error(this.$t('m.Passwordinconsistency')))
      } else {
        callback()
      }
    }
    return {
      // 忘记密码步骤： 1-next 2-submit
      forgetPwdStep: 1,
      // 发送验证码标识
      msgKey: false,
      msgText: this.$t('m.Login_Verification_Code_Send'),
      msgTime: 60,
      form: {
        // 登入类型：1-账号密码 2-验证码
        type: 1,
        // 短信验证码
        msgCode: '',
        // 国家码
        code: this.$country.codes,
        phone: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        phone: [
          {
            required: true,
            validator: validatorCodePhone,
            trigger: ['blur', 'change']
          }
        ],
        msgCode: this.$rule.msgCode,
        password: [
          { required: true, trigger: 'blur', validator: checkPassword }
        ],
        confirmPassword: [
          { validator: checkPasswords, required: true, trigger: 'blur' }
        ]
      },
      codeWidth: ''
    }
  },
  computed: {
    widthStyle () {
      return {
        '--codeWidth': this.codeWidth
      }
    },
    getLang () {
      return this.$cache.getLang() ? this.$cache.getLang() : 'EN'
    }
  },
  created () {
    this.getCountry()
  },
  mounted () {
    this.getWidth()
  },
  beforeRouteEnter (to, from, next) {
    document
      .querySelector('body')
      .setAttribute('style', 'background-color:#e4e4eb')
    next()
  },

  beforeRouteLeave (to, from, next) {
    document.querySelector('body').removeAttribute('style')
    next()
  },
  methods: {
    //获取下拉框宽度
    getWidth () {
      let box = document.getElementById('box')
      this.codeWidth = box.clientWidth + 32 + 'px'
    },
    // 获取国家信息
    getCountry () {
      const country = this.$cache.getCountry()
      // console.log('getCountry', country)
      if (country) {
        this.country = country
        this.form.code = country.codes
      } else {
        this.country = this.$country
        this.form.code = this.$country.codes
      }
    },
    changePhone (val) {
      this.form.phone = this.$check.onlyNum(val)
    },
    changeCode (val) {
      this.form.msgCode = this.$check.onlyNum(val)
    },
    //密码输入限制
    changePassword (val) {
      this.form.password = this.$check.password(val)
    },
    changePasswords (val) {
      this.form.confirmPassword = this.$check.password(val)
    },
    // 时间计算
    timeCalc () {
      // 计时避免重复发送
      this.msgText = this.msgTime + ' s'
      this.msgKey = true
      const time = setInterval(() => {
        this.msgTime--
        this.msgText = this.msgTime + ' s'
        if (this.msgTime === 0) {
          this.msgTime = this.$options.data.call(this).msgTime
          this.msgText = this.$options.data.call(this).msgText
          this.msgKey = false
          clearInterval(time)
        }
      }, 1000)
    },
    // 处理发送验证码
    handleSend () {
      // 判断是否可以发送（时间限制）
      if (this.msgKey) return
      const param = {
        code: this.form.code,
        phone: this.form.phone,
        scene: 3
      }
      // 发送验证码
      let props = 'phone'
      this.$refs.form.validateField(props, valid => {
        // console.log('valid ' + props, valid)
        if (!valid) {
          this.$api.login.getCode(param).then(res => {
            if (this.$ok(res)) {
              this.timeCalc()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },

    submit () {
      // 忘记密码步骤1参数校验
      if (this.forgetPwdStep == 1) {
        const props = ['msgCode', 'phone']
        let errList = []
        this.$refs.form.validateField(props, async errorMsg => {
          // console.log('field', errorMsg, props, errList)
          errList.push(errorMsg)
          if (
            errList.length == props.length &&
            errList.every(item => item == '')
          ) {
            // 校验验证码
            this.$api.login
              .checkoutCode(this.form.phone, this.form.msgCode, this.form.code)
              .then(res => {
                if (this.$ok(res)) {
                  // 步骤1 -> 步骤2
                  this.forgetPwdStep = 2
                } else {
                  this.$message.error(res.message)
                }
              })
          }
        })
      } else {
        this.$refs.form.validate(valid => {
          // console.log(valid, this.form)
          if (!valid) {
            return
          }
          const param = { ...this.form }
          // 数据处理
          if (this.form.password) {
            param.password = this.$md5(this.form.password)
          }
          if (this.form.confirmPassword) {
            param.confirmPassword = this.$md5(this.form.confirmPassword)
          }
          // 步骤2 -> 提交
          if (this.forgetPwdStep == 2) {
            this.$openLoading({ target: '.sign_div' })
            this.$api.login.resetPassword(param).then(res => {
              this.$closeLoading()
              if (this.$ok(res)) {
                this.$message.success(res.message)
                this.resetParam()
                this.jump('/login')
              } else {
                this.$message.error(res.message)
              }
            })
          }
        })
      }
    },
    // 重置参数
    resetParam () {
      this.form = this.$options.data.call(this).form
      this.forgetPwdStep = this.$options.data.call(this).forgetPwdStep
    },
    // 选择区号
    selectCountry (data) {
      // console.log('country select', data)
      this.$nextTick(() => {
        this.getWidth()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  min-width: 1200px !important;
  overflow-x: hidden !important;
  overflow-y: auto !important;
  padding: 0 !important;
}

.sign_in {
  display: flex;
  min-height: 100vh;
  .login_img {
    position: relative;
    background: url('@/assets/imgs/login/login_joltzly.jpg') center / cover
      no-repeat;
    width: 67.77778%;
    .login_logo {
      position: absolute;
      width: 64px;
      height: 64px;
      top: 24px;
      left: 24px;
    }
  }
  .sign_div {
    position: relative;
    display: flex;
    flex: 1;
    min-width: 400px;
    background-color: #fff;

    .login_form {
      display: flex;
      flex: 1;
      width: 100%;
      .login_item {
        width: 100%;
        padding: 0 10.35%;
      }
    }

    .sign_top {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      margin: 60px 0 100px 0;
      .sign_top_select {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 40px;
        // background: #f5f5f7;
        border-radius: 10px;
        padding: 0 15px;
      }
    }

    .sign_title {
      padding: 12px 0 12px 8px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .sign_title_login {
        font-size: 23px;
        font-weight: 700;
        text-align: left;
        color: #39404d;
        line-height: 28px;
      }
    }

    .sign_form_title {
      font-size: 17px;
      font-weight: 600;
      text-align: left;
      color: #39404d;
      line-height: 20px;
      margin: 16px 0 8px 6px;
    }

    .sign_form_input {
      // width: 368px;

      &::placeholder {
        font-size: 14px;
        font-weight: 500;
        text-align: left;
        color: #99999b;
        line-height: 16px;
      }

      ::v-deep .el-input__inner {
        width: 100%;
        height: 56px !important;
        background: #ffffff;
        border: 1px solid #e4e4e6;
        border-radius: 10px;
        padding-left: 16px !important;
        font-size: 14px;
        font-weight: 500;
        text-align: left;
        // color: #39404d;
        line-height: 16px;
      }
    }

    .sign_form_input2 {
      ::v-deep .el-input__inner {
        padding-left: var(--codeWidth) !important;
      }
    }

    .sign_form_phone {
      position: relative;

      .country_code {
        position: absolute;
        z-index: 999;
        left: 16px;
        top: 20px;
      }
    }

    .sign_form_code {
      position: relative;

      .sign_code {
        position: absolute;
        right: 12px;
        bottom: 12px;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        min-width: 80px;
        padding: 0 8px;
        height: 32px;
        background: $color;
        border-radius: 4px;
        font-weight: 500;
        font-size: 14px;
      }

      .sign_code_disabled {
        opacity: 0.4;
      }
      ::v-deep .el-input__suffix {
        right: 105px !important;
      }
    }

    .sign_btn {
      width: 100%;
      height: 56px;
      background: $color;
      border-radius: 10px;
      font-size: 17px;
      font-weight: 600;
      text-align: center;
      color: #ffffff;
      line-height: 20px;
      margin-top: 24px;
      margin-left: 0px;
    }

    .sign_bottom {
      margin-top: 16px;
      margin-bottom: 40px;
      width: 100%;
      font-size: 14px;
      font-weight: 500;
      text-align: center;
      color: #39404d;
      line-height: 16px;

      span {
        font-size: 14px;
        font-weight: 500;
        text-align: left;
        color: $color;
        line-height: 16px;
        cursor: pointer;

        .el-icon-arrow-right {
          font-size: 9px;
          color: $color;
          font-weight: 700;
          line-height: 16px;
        }
      }
    }

    ::v-deep .el-form-item__error {
      left: 6px !important;
    }

    ::v-deep .el-form-item {
      margin-bottom: 16px;
    }
    ::v-deep .is-error {
      margin-bottom: 24px;
    }

    ::v-deep .el-form-item.is-error .el-input__inner,
    .el-form-item.is-error .el-input__inner:focus,
    .el-form-item.is-error .el-textarea__inner,
    .el-form-item.is-error .el-textarea__inner:focus {
      border-color: #fd5849;
    }
  }
}
</style>
